package cn.hloger.spider.demo.webSocketDemo.client;

import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.net.URI;
import java.util.Scanner;

/**
 * socket的客户端
 *
 * @author huanglong
 * @version 1.0
 * @date 2024/2/27
 */
@ClientEndpoint
public class WebSocketClient2 {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("链接成功");
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("服务器回复: " + message);
    }

    public static void main(String[] args) {
        try {
            String ip = "127.0.0.1";
            String port = "8280";
            String path = "/chat";
            String id = "/3333333";
            String name = "?name=qianqian";
            String uri = "ws://" + ip + ":" + port + path + id + name;
            System.out.println(uri);
            //开启socket
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            Session session = container.connectToServer(WebSocketClient2.class, URI.create(uri));
            while (true) {
                Scanner scanner = new Scanner(System.in);
                String userInput = scanner.nextLine();
                session.getBasicRemote().sendText(userInput);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
